import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shensu/common/model/game.dart';
import 'package:flutter_shensu/common/style/AiSuColors.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_shensu/common/util/navigator_utils.dart';
import 'package:flutter_shensu/common/util/network_utils.dart';
import 'package:device_apps/device_apps.dart';

class MyISpeedPage extends StatefulWidget {
  _MyISpeedPageState createState() => _MyISpeedPageState();
}

class _MyISpeedPageState extends State<MyISpeedPage>
    with AutomaticKeepAliveClientMixin<MyISpeedPage> {
  List<Game> _gameList = [];

  @override
  void initState() {
    super.initState();
    getAllGameList();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(AiSuColors.primaryAiSuValue),
          title: const Text('加速'),
        ),
        body: Center(
          child: _getBody(),
        ));
  }

  Widget layout(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(AiSuColors.primaryAiSuValue),
          title: const Text('加速'),
        ),
        body: Center(
          child: _getBody(),
        ));
  }

  Widget _getBody() {
    if (_gameList.length != 0) {
      return ListView.builder(
          itemCount: _gameList.length,
          itemBuilder: (context, i) {
            return _buildItem(_gameList[i]);
          });
    } else {
      return Center(
        child: CupertinoActivityIndicator(),
      );
    }
  }

  Widget header(BuildContext context) {
    return ListTile(
      title: Text('ListTitle'),
    );
  }

  void getAllGameList() async {
    if (_gameList.length == 0) {
      // 判断是安卓还是ios
      if (Platform.isIOS) {
        //ios相关代码
        _getiOSGameList();
      } else {
        //android相关代码
        _getAndroidGameList();
      }
    }
  }

  void _getAndroidGameList() async {
    List<Game> allGameList = await NetWorkUtils.instance.getAllGameList();
    List<Application> appsList = await DeviceApps.getInstalledApplications();
    print(appsList.length);

    List<Game> appGameList = new List();
    int allGameLength = allGameList.length;
    int appsListLength = appsList.length;
    if (allGameLength != 0 && appsListLength != 0) {
      allGameList.forEach((game) {
        String gameName = game.app_name.trim();
        appsList.forEach((app) {
          String appPackageName = app.packageName.trim();
          if (gameName == appPackageName) {
            appGameList.add(game);
          }
        });
      });
    }

    setState(() {
      _gameList = appGameList;
    });
  }

  void _getiOSGameList() async {
    List<Game> future = await NetWorkUtils.instance.getAllGameList();
    setState(() {
      _gameList = future;
    });
  }

  @override
  bool get wantKeepAlive => true;

  Widget _buildItem(Game game) {
    return Column(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.fromLTRB(0, 5, 0, 5),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: const EdgeInsets.fromLTRB(16, 0, 15, 0),
                width: 64.0,
                height: 64.0,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                  Radius.circular(15.0),
                )),
                child: CachedNetworkImage(
                  imageUrl: game.game_icon_url,
                  placeholder: new CircularProgressIndicator(
                    strokeWidth: 2.0,
                  ),
                  errorWidget: new Icon(Icons.error),
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new Container(
                      padding: const EdgeInsets.only(bottom: 1.0),
                      child: Text(
                        game.game_name_zh,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: Colors.black, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Text(
                      game.game_desc,
                      style: TextStyle(color: Colors.grey[500]),
                    )
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                child: RaisedButton(
                  color: Color(AiSuColors.primarySpeedValue),
                  onPressed: () {
                    NavigatorUtils.goISpeedPage(context, game);
                  },
                  textColor: Colors.white,
                  child: Text('加速'),
                ),
              ),
            ],
          ),
        ),
        Divider()
      ],
    );
  }
}
